﻿using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace DevelopmentKit.Framework
{
    public class Serialization
    {
        /// <summary>
        /// 将XML字符串反序列化为一个对象
        /// </summary>
        /// <typeparam name="T">对象的类型</typeparam>
        /// <param name="xml">需要反序列化的XML字符串</param>
        /// <returns>对象的实例</returns>
        public static T XmlToObject<T>(string xml) where T : class
        {
            using (var ms = new MemoryStream())
            {
                using (var sr = new StreamWriter(ms, Encoding.UTF8))
                {
                    sr.Write(xml);
                    sr.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    var serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(ms) as T;
                }
            }
        }

        /// <summary>
        /// 将一个对象序列化为XML字符串
        /// </summary>
        /// <typeparam name="T">对象的类型</typeparam>
        /// <param name="obj">对象XML字符串</param>
        /// <returns>对象的实例</returns>
        public static string ObjectToXml<T>(T obj) where T : class
        {  
            using (var mem = new MemoryStream())
            {

                var ser = new XmlSerializer(obj.GetType());
                var writer = new XmlTextWriter(mem, Encoding.UTF8);
                ser.Serialize(writer, obj);
                writer.Close();
                return Encoding.UTF8.GetString(mem.ToArray());
            }

        }
    }
}
